package com.deepglint.tableapi.udf;

import com.deepglint.beans.SensorReading;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.functions.TableFunction;
import org.apache.flink.table.planner.expressions.In;
import org.apache.flink.types.Row;
import org.apache.flink.types.Value;

/**
 * @author mj
 * @version 1.0
 * @date 2021-11-28 18:56
 * 将一条数据，拆分成多条
 */
public class UDFTest_TableFunction {
    public static void main(String[] args) throws Exception {
        // 1.创建环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        // 2.读取数据
        String path = "C:\\Users\\马军\\Desktop\\Idea-workspace\\flink\\src\\main\\resources\\source.txt";
        DataStreamSource<String> sourceStream = env.readTextFile(path);

        // 3.转换pojo
        SingleOutputStreamOperator<SensorReading> mapStream = sourceStream.map(line -> {
            String[] split = line.split(",");
            return new SensorReading(split[0], split[1], new Long(split[2]), new Double(split[3]));
        });

        // 4.将流转换为表
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);
        Table sensorTable = tableEnv.fromDataStream(mapStream, "id,timestamp as ts,temperature as temp");
        tableEnv.createTemporaryView("sensor", sensorTable);

        // 5. 自定义的table函数，实现id拆分，输出(word，length)
        // 5.1 table api

        // 环境中注册函数
        MyTableFunction tableFunction = new MyTableFunction();
        tableEnv.registerFunction("split", tableFunction);
        Table resultTable = sensorTable.joinLateral("split(id) as (word,len)")
                .select("word,len");

        // 5.2
        Table sqlQuery = tableEnv.sqlQuery("select id,ts,word,len from sensor,lateral table(split(id)) as splitid(word,len)");

        // 输出
        tableEnv.toAppendStream(resultTable, Row.class).print("table");
        tableEnv.toAppendStream(sqlQuery, Row.class).print("sql");

        env.execute();
    }

    // 实现自定义TableFunction
    public static class MyTableFunction extends TableFunction<Tuple2<String, Integer>> {

        // 写一个eval，没有返回值
        public void eval(String vale) {
            String[] split = vale.split("\\d");
            collect(new Tuple2<>(split[0], split[0].length()));
        }
    }
}
